package com.moleq.mgpos.activities;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.TextView;
import com.moleq.base.MoleQBaseActivity;
import com.moleq.base.MoleQBaseDialog;
import com.moleq.device.BasePinPad;
import com.moleq.device.DeviceManager;
import com.moleq.device.PaxPinPad;
import com.moleq.device.PaxPinPadSetting;
import com.moleq.dialog.MessageBox;
import com.moleq.dialog.MessageDialog;
import com.moleq.dialog.MessageDialog.OnClickMessageListener;
import com.moleq.dialog.StringSourceDialog;
import com.moleq.logic.PosPrinter;
import com.moleq.logic.Report;
import com.moleq.models.GlobalInfo;
import com.moleq.service.ServiceManager;
import com.pax.poslink.CommSetting;
import com.pax.poslink.PosLink;
import com.pax.poslink.ProcessTransResult;
import com.pax.poslink.ReportRequest;
import com.pax.poslink.ReportResponse;
import com.pax.poslink.ProcessTransResult.ProcessTransResultCode;

public class TerminalReportActivity extends MoleQBaseActivity implements OnClickListener, Runnable {

	public static final int DIALOG_TRANSTYPE = 601;
	public static final int DIALOG_EDCTYPE = 602;
	public static final int DIALOG_CARDTYPE = 603;
	public static final int DIALOG_PAYMENTTYPE = 604;
	
	private Button btn_go, btn_print, btn_exit, btn_transType,btn_edcType,btn_cardType,btn_paymentType;
	private TextView tv_content;
	private List<String> transSource = new ArrayList<String>();
	private List<String> edcSource = new ArrayList<String>();
	private List<String> cardSource = new ArrayList<String>();
	private List<String> paymentSource = new ArrayList<String>();
	
	public static final int TRANSACTION_SUCCESSED = 100;  //transaction success
    public static final int TRANSACTION_FAILURE = 101; //transaction failure
    public static final int TRANSACTION_TIMEOOUT = 102; //transaction timeout
    public static final String DIALOG_TITLE = "Title"; //dialog title
    public static final String DIALOG_MESSAGE = "Message";//dialog message
    private static final String TAG = "PaxReportActivity";
	private ProgressDialog mPayingProgress = null;
	private DeviceManager mDeviceManager;
	
	private Handler mHandler = new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case TRANSACTION_SUCCESSED:
				mPayingProgress.dismiss();
				ReportResponse response = (ReportResponse) msg.obj;
				setReportResponse(response);
				break;
			case TRANSACTION_TIMEOOUT:
				 MessageBox.show(TerminalReportActivity.this, msg.getData().getString(DIALOG_MESSAGE));
			case TRANSACTION_FAILURE:
				mPayingProgress.dismiss();
				String title = msg.getData().getString(DIALOG_TITLE);
				String message = msg.getData().getString(DIALOG_MESSAGE);
				MessageBox.show(TerminalReportActivity.this, message);
				break;
			}
		}
	};
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_terminal_report);
		
		tv_content = (TextView) findViewById(R.id.tv_content);
		btn_go = (Button) findViewById(R.id.btn_go);
		btn_print = (Button) findViewById(R.id.btn_print);
		btn_exit = (Button) findViewById(R.id.btn_exit);
		btn_transType = (Button) findViewById(R.id.btn_transType);
		btn_edcType = (Button) findViewById(R.id.btn_edcType);
		btn_cardType = (Button) findViewById(R.id.btn_cardType);
		btn_paymentType = (Button) findViewById(R.id.btn_paymentType);
		
		btn_go.setOnClickListener(this);
		btn_print.setOnClickListener(this);
		btn_exit.setOnClickListener(this);
		btn_transType.setOnClickListener(this);
		btn_edcType.setOnClickListener(this);
		btn_cardType.setOnClickListener(this);
		btn_paymentType.setOnClickListener(this);
		
		transSource.add("LOCAL TOTAL");
		transSource.add("LOCAL DETAIL");
		transSource.add("LOCAL FAILED");
		transSource.add("HOST");
		transSource.add("HISTORY");
		btn_transType.setText("LOCAL TOTAL");
		
		edcSource.add("[EMPTY]");
		edcSource.add("ALL");
		edcSource.add("CREDIT");
		edcSource.add("DEBIT");
		edcSource.add("CHECK");
		edcSource.add("EBT");
		edcSource.add("GIFT");
		edcSource.add("LOYALTY");
		edcSource.add("CASH");
		btn_edcType.setText("[EMPTY]");
		
		cardSource.add("[EMPTY]");
		cardSource.add("VISA");
		cardSource.add("MASTERCARD");
		cardSource.add("AMEX");
		cardSource.add("DISCOVER");
		cardSource.add("OTHER");
		btn_cardType.setText("[EMPTY]");
		
		paymentSource.add("[EMPTY]");
		paymentSource.add("UNKNOWN");
		paymentSource.add("AUTH");
		paymentSource.add("SALE");
		paymentSource.add("RETURN");
		paymentSource.add("VOID");
		paymentSource.add("POSTAUTH");
		paymentSource.add("FORCEAUTH");
		paymentSource.add("ADJUST");
		paymentSource.add("INQUIRY");
		paymentSource.add("ACTIVATE");
		paymentSource.add("DEACTIVATE");
		paymentSource.add("RELOAD");
		paymentSource.add("VOID SALE");
		paymentSource.add("VOID RETURN");
		paymentSource.add("VOID AUTH");
		paymentSource.add("VOID RETURN");
		paymentSource.add("VOID POSTAUTH");
		paymentSource.add("VOID FORCEAUTH");
		paymentSource.add("VOID WITHDRAWAL");
		paymentSource.add("REVERSAL");
		paymentSource.add("WITHDRAWAL");
		paymentSource.add("ISSUE");
		paymentSource.add("CASHOUT");
		paymentSource.add("REPLACE");
		paymentSource.add("MERGE");
		paymentSource.add("REPORTLOST");
		paymentSource.add("REDEEM");
		paymentSource.add("VERIFY");
		paymentSource.add("REACTIVATE");
		paymentSource.add("FORCED ISSUE");
		paymentSource.add("FORCED ADD");
		btn_paymentType.setText("[EMPTY]");
		
		mPayingProgress = creatProgressDialog(TerminalReportActivity.this);
		mDeviceManager = DeviceManager.getInstance();
		mDeviceManager.resetALLDevices();
		
//		PaxPinPad mPaxPinPad = new PaxPinPad(absoluteDir);
//		
//        CommSetting commset = new CommSetting(getApplicationContext().getFilesDir().getAbsolutePath());
//        commset.CommType = "UART";
//        commset.TimeOut = "30000";
//        commset.SerialPort = "COM2";
//        commset.DestIP = "";
//        commset.DestPort = "";
//        commset.SaveCommSettingFile();
		
		PaxPinPadSetting posDevSetting = new PaxPinPadSetting();
		posDevSetting = ServiceManager.getInstance().mPinPadService.getPinPadSetting();
		if (posDevSetting == null)
			mDeviceManager.pinPadIsReady = false;
		else
			mDeviceManager.pinPadIsReady = true;
		if (mDeviceManager.pinPadIsReady) {
			BasePinPad posdev = new PaxPinPad(getApplicationContext().getFilesDir().getAbsolutePath());
			posdev.setPinPadSetting(posDevSetting);
			posdev.isUploadSignatureCapture = GlobalInfo.getInstance().isSigHost;
			mDeviceManager.setPinPad(posdev);
			mDeviceManager.pinPad.onConnect();
			mDeviceManager.pinPad.initialize();
		}
	}
	
	public static ProgressDialog creatProgressDialog(Context context) {
        ProgressDialog dialog = new ProgressDialog(context);
        dialog.setMessage("Please wait...");
        dialog.setIndeterminate(true);
        dialog.setCancelable(true);
        dialog.setCanceledOnTouchOutside(false);
        return dialog;
    }
	
	private void setReportRequest(ReportRequest request) {
		request.TransType = request.ParseTransType(getReportType(btn_transType.getText().toString()));
		request.EDCType = request.ParseEDCType(btn_edcType.getText().toString());
		request.CardType = request.ParseCardType(btn_cardType.getText().toString());
		request.PaymentType = request.ParsePaymentType(btn_paymentType.getText().toString());
	}
	
	private void setReportResponse(ReportResponse response) {
    	String result = "";
    	Report report = new Report("PaxReport");
    	result = report.getPaxResult(response);
    	tv_content.setText(result);
    }
	
	public String getReportType(String type){
		String result = "";
		
//		transSource.add("LOCAL TOTAL");
//		transSource.add("LOCAL DETAIL");
//		transSource.add("LOCAL FAILED");
//		transSource.add("HOST");
//		transSource.add("HISTORY");
		
		if (type.equals("LOCAL TOTAL")) {
			result = "LOCALTOTALREPORT";
		}else if(type.equals("LOCAL DETAIL")){
			result = "LOCALDETAILREPORT";
		}else if(type.equals("LOCAL FAILED")){
			result = "LOCALFAILEDREPORT";
		}else if(type.equals("HOST")){
			result = "HOSTREPORT";
		}else if(type.equals("HISTORY")){
			result = "HISTORYREPORT";
		}
		
		return result;
	}
	
	private OnClickMessageListener onClickMessageListener = new OnClickMessageListener() {

		public void onClickYes() {
			finish();
		}

		public void onClickNo() {

		}

		public void onClickOK() {

		}
	};
	
	public void Keyboard() {
		try {
			InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
			inputMethodManager.hideSoftInputFromWindow(TerminalReportActivity.this
					.getCurrentFocus().getWindowToken(),
					InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (Exception e) {
			return;
		}
	}

	@Override
	public void onCloseWithReturn(Class<? extends MoleQBaseDialog> pramClass, int viewId, String parm) {
		super.onCloseWithReturn(pramClass, viewId, parm);

		switch (viewId) {
		default:
			break;
		}
	}
	
	private void process() {
	    ReportRequest reprequest = new ReportRequest();
	    setReportRequest(reprequest);
	    Log.i(TAG, "ReportRequest.TransType = " + reprequest.TransType);
	    // create Poslink object
	    PosLink poslink = new PosLink();
	
	    // set the folder to save the "comsetting.ini" file
	    poslink.appDataFolder = getApplicationContext().getFilesDir().getAbsolutePath();
	    poslink.ReportRequest = reprequest;
	
	    // ProcessTrans is Blocking call, will return when the transaction is
	    // complete.
	    ProcessTransResult ptr = poslink.ProcessTrans();
	    // There will be 2 separate results that you must handle. First is the
	    // ProcessTransResult, this will give you the result of the
	    // request to call poslink. ReportResponse should only be checked if
	    // ProcessTransResultCode.Code == OK.
	
	    if (ptr.Code == ProcessTransResultCode.OK) {
	        ReportResponse response = poslink.ReportResponse;
	        Message msg = new Message();
	        msg.what = TRANSACTION_SUCCESSED;
	        msg.obj = response;
	        mHandler.sendMessage(msg);
	
	        Log.i(TAG, "Transaction sucessed!");
	
	    } else if (ptr.Code == ProcessTransResultCode.TimeOut) {
	        Message msg = new Message();
	        msg.what = TRANSACTION_TIMEOOUT;
	        Bundle b = new Bundle();
	        b.putString(DIALOG_TITLE, String.valueOf(ptr.Code));
	        b.putString(DIALOG_MESSAGE, ptr.Msg);
	        msg.setData(b);
	        mHandler.sendMessage(msg);
	
	        Log.e(TAG, "Transaction TimeOut! " + String.valueOf(ptr.Code));
	        Log.e(TAG, "Transaction TimeOut! " + ptr.Msg);
	    } else {
	        Message msg = new Message();
	        msg.what = TRANSACTION_FAILURE;
	        Bundle b = new Bundle();
	        b.putString(DIALOG_TITLE, String.valueOf(ptr.Code));
	        b.putString(DIALOG_MESSAGE, ptr.Msg);
	        msg.setData(b);
	        mHandler.sendMessage(msg);
	
	        Log.e(TAG, "Transaction Error! " + String.valueOf(ptr.Code));
	        Log.e(TAG, "Transaction Error! " + ptr.Msg);
	    }
	}
	 
	 @Override
	    public void run() {
	        // processTransactions
	        process();

	    }
	
	@Override
	public void onReturnValue(int what, Object obj) {
		// TODO Auto-generated method stub
		switch (what) {
		case DIALOG_TRANSTYPE:
			String trans = (String) obj;
			btn_transType.setText(trans);
			break;
		case DIALOG_EDCTYPE:
			String edc = (String) obj;
			btn_edcType.setText(edc);
			break;
		case DIALOG_CARDTYPE:
			String card = (String) obj;
			btn_cardType.setText(card);
			break;
		case DIALOG_PAYMENTTYPE:
			String payment = (String) obj;
			btn_paymentType.setText(payment);
			break;
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		StringSourceDialog mStringSourceDialog = null;
		String transType,edcType,cardType,paymentType;
		switch (v.getId()) {
		case R.id.btn_transType:
			transType = btn_transType.getText().toString();
			mStringSourceDialog = new StringSourceDialog(TerminalReportActivity.this, TerminalReportActivity.this);
			mStringSourceDialog.setSource(transSource, transType, DIALOG_TRANSTYPE);
			mStringSourceDialog.show();
			break;
		case R.id.btn_edcType:
			edcType = btn_edcType.getText().toString();
			mStringSourceDialog = new StringSourceDialog(TerminalReportActivity.this, TerminalReportActivity.this);
			mStringSourceDialog.setSource(edcSource, edcType, DIALOG_EDCTYPE);
			mStringSourceDialog.show();
			break;
		case R.id.btn_cardType:
			cardType = btn_cardType.getText().toString();
			mStringSourceDialog = new StringSourceDialog(TerminalReportActivity.this, TerminalReportActivity.this);
			mStringSourceDialog.setSource(cardSource, cardType, DIALOG_CARDTYPE);
			mStringSourceDialog.show();
			break;
		case R.id.btn_paymentType:
			paymentType = btn_paymentType.getText().toString();
			mStringSourceDialog = new StringSourceDialog(TerminalReportActivity.this, TerminalReportActivity.this);
			mStringSourceDialog.setSource(paymentSource, paymentType, DIALOG_PAYMENTTYPE);
			mStringSourceDialog.show();
			break;
		case R.id.btn_go:
			tv_content.setText("");
			 mPayingProgress.show();
			 Thread thread = new Thread(this);
             thread.start();
             break;
		case R.id.btn_print:
			String context = tv_content.getText().toString();
			if(context.trim().equals("")) return;
			PosPrinter printer = new PosPrinter();
			if(!printer.isBusy()){
				printer.onConnect();
				printer.print(context);
				printer.cutPaper();
				printer.onDisconnect();
			}
			break;
		case R.id.btn_exit:
			MessageBox.show(TerminalReportActivity.this, getResources().getString(R.string.msg_exit_program), onClickMessageListener, MessageDialog.MESSAGE_BOX_YES_NO);
			break;
		}
	}
}
